package com.woniuxy.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.dto.commonDto.BaseDto;
import com.woniuxy.param.PageQueryParam;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * redis工具类
 *
 * @author 周川雄
 * @date 2022/1/3 20:38
 */
public class RedisUtil {

    private StringRedisTemplate stringRedisTemplate;
    private ObjectMapper objectMapper;

    public RedisUtil(StringRedisTemplate stringRedisTemplate, ObjectMapper objectMapper) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.objectMapper = objectMapper;
    }

    public <T> List<T> getAllRedis(String h, Class<T> type) {
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(h);
        List<T> list = new ArrayList<>();

        try {
            for (Object k : map.keySet()) {
                list.add(objectMapper.readValue(map.get(k).toString(), type));
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return WoniuBeanUtils.copyList(list, type);
    }


    /**
     * 手动分页
     *
     * @param dataList 被分页的集合
     * @param <T>      集合中的对象类型泛型
     * @return BaseDto<T>
     */
    public <T> BaseDto<T> page(List<T> dataList, PageQueryParam pageQueryParam) {

        List<T> currentPageList = new ArrayList();
        BaseDto<T> baseDto = new BaseDto<>();
        long currentPage = pageQueryParam.getIndexPage();
        long pageSize = pageQueryParam.getPageSize();

        if (dataList != null && dataList.size() > 0) {
            long currIdx = (currentPage > 1 ? (currentPage - 1) * pageSize : 0);

            long pageCount = dataList.size() / pageSize;
            if (dataList.size() % pageSize > 0) {
                pageCount++;
            }
            baseDto.setPageCount(pageCount);

            for (int i = 0; i < pageSize && i < dataList.size() - currIdx; i++) {
                T data = dataList.get((int) (currIdx + i));
                currentPageList.add(data);
            }
            baseDto.setIndexPage(currentPage);
            baseDto.setList(currentPageList);
        }
        return baseDto;
    }

}
